package com.zthz.douxing.data

import com.zthz.douxing.PlantripService
import com.zthz.douxing.SegmentStatus
import com.zthz.douxing.TripSegment
import com.zthz.douxing.event.UpdateTripSegmentStatusEvent
import com.zthz.douxing.utils.CommonUtil
import org.quartz.Job
import org.quartz.JobExecutionContext
import org.quartz.JobExecutionException

class TripSegmentStatusUpdateJob {
    def eventBusService

    static triggers = {
        //每天执行一次
        cron name: 'searchTodayTripSegmentJob', cronExpression: '0 0 */9 * * ?'
    }
    def group = "tripSegmentStatusUpdateJob"

    /**
     * 执行当前日期的行程。如果是主host机器。
     * @param context
     * @return
     */
    def execute(JobExecutionContext context) {
        try {
            if(CommonUtil.isMasterHost()){
                getSegementTrips(context)
            } else {
                log.info("当前主机不是master，忽略这次执行！")
            }
        } catch (Exception e) {
            log.debug(e.getMessage(), e)
        }
    }

    /**
     *
     * @param context
     */
    private void getSegementTrips(JobExecutionContext context) {
        def query = "from TripSegment as ts where ts.startTime > ? and ts.startTime < ? and ts.segmentStatus == ?"
        def currentTime = new Date()
        def nextFireTime = context.nextFireTime
        def datas = TripSegment.findAll(query, [currentTime, nextFireTime, SegmentStatus.WillGo])
        datas?.each { segment ->
            UpdateTripSegmentStatusEvent event = new UpdateTripSegmentStatusEvent()
            event.tripSegment = segment
            event.plantripEndTime = segment.plantrip.endDate
            eventBusService.post(event)
        }
    }
}

class TripSegmentOnPositionJob implements Job {
    @Override
    void execute(JobExecutionContext context) throws JobExecutionException {
        UpdateTripSegmentStatusEvent event = context.getMergedJobDataMap().get("tripSegmentEvent")
        PlantripService service = context.getMergedJobDataMap().get("plantripService")

        service.updateTripSegmentStatus(event.tripSegment, "1", null)
    }
}

class TripSegmentArrivedJob implements Job {
    @Override
    void execute(JobExecutionContext context) throws JobExecutionException {
        UpdateTripSegmentStatusEvent event = context.getMergedJobDataMap().get("tripSegmentEvent")
        Date endTime = event.plantripEndTime
        PlantripService service = context.getMergedJobDataMap().get("plantripService")

        service.updateTripSegmentStatus(event.tripSegment, "2", endTime)
    }
}